class Solution:
    def nextClosestTime(self, time: str) -> str:
        hour1, minute1 = time.split(":")
        numbers = set(hour1 + minute1)
        hour2 = hour1
        minute2 = minute1

        # 寻找更大的分钟
        for i in range(int(minute1) + 1, 60):
            minute = str(i).zfill(2)
            if minute[0] in numbers and minute[1] in numbers:
                return hour2 + ":" + minute

        # 寻找更大的小时
        for i in range(int(hour1) + 1, 24):
            temp = str(i).zfill(2)
            if temp[0] in numbers and temp[1] in numbers:
                hour2 = temp
                break

        # 寻找最小的分钟
        for i in range(0, 60):
            temp = str(i).zfill(2)
            if temp[0] in numbers and temp[1] in numbers:
                minute2 = temp
                break

        # 这一天还有更大的小时
        if hour1 != hour2:
            return hour2 + ":" + minute2

        # 寻找下一天里最小的小时
        for i in range(0, 23):
            hour2 = str(i).zfill(2)
            if hour2[0] in numbers and hour2[1] in numbers:
                return hour2 + ":" + minute2

        # 无法改变
        return hour1 + ":" + minute1


if __name__ == "__main__":
    print(Solution().nextClosestTime("19:34"))  # "19:39"
    print(Solution().nextClosestTime("23:59"))  # "22:22"
    print(Solution().nextClosestTime("00:00"))  # "00:00"
